package com.zdp.feignclient.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author sesshomaru
 * @date 2021/7/28 21:13
 *
 * 也就是再feign发起请求前给请求携带上header，这里还以携带别的东西
 * feign的拦截器，用于为请求feign接口时携带上token
 * 配置方式1 @FeignClient中通过configuration配置
 * 配置方式2 需要在配置文件中配置一下
 */
public class TokenRelayRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 1.获取到上游请求的token
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String token = httpServletRequest.getHeader("token");
        // TODO 判断token是否存在
        if (StringUtils.isBlank(token)) {
            token = "123";
        }
        // 2.传递token(把某一个值传到feign请求的请求头中去)
        requestTemplate.header("token", token);
    }
}
